package com.aaa.redis;

import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class RedisCache implements Cache{
    private RedisTemplate redisTemplate;
    private final String id;
    // cache instance id
    private static final long EXPIRE_TIME_IN_MINUTES = 30;

    // redis过期时间
    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }

    public RedisCache(String id) {
        if (null == id) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object o, Object o1) {
        getRedisTemplate();
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set(o, o1, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
        System.out.println("放入结果到缓存:" + o);
    }

    @Override
    public Object getObject(Object o) {
        getRedisTemplate();
        System.out.println(o);
        System.out.println(redisTemplate);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        System.out.println("获取结果从缓存:" + o);
        return opsForValue.get(o);
    }

    @Override
    public Object removeObject(Object o) {
        getRedisTemplate();
        return redisTemplate.delete(o);
    }

@Override
public void clear() {
        getRedisTemplate();
        redisTemplate.execute((RedisCallback) connection -> {
        connection.flushDb();
        return null;
        });
        System.out.println("清空缓存");
        }

    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return new ReentrantReadWriteLock();
    }
        }